// import { useState } from 'react'
// import { Button } from 'antd' //按需引入即可
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { Menu } from 'antd'
import type { MenuProps } from 'antd'
import { useState, useEffect } from 'react'
import { Route, Routes, useNavigate, useLocation } from 'react-router-dom'
import indexRouter from '@/router/index'

type MenuItem = Required<MenuProps>['items'][number]

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem
}

const items: MenuItem[] = [
  getItem('about', '/about', <PieChartOutlined />),
  getItem('user', '/user', <DesktopOutlined />),
  getItem('page', 'sub1', <UserOutlined />, [
    getItem('page1', '/page1'),
    getItem('page2', '/page2'),
  ]),
  getItem('sub', 'sub2', <UserOutlined />, [
    getItem('sub1', '/sub1'),
    getItem('sub2', '/sub2'),
  ]),
]
const HomeMenu: React.FC = () => {
  // 执行useNavigate()的得到一个跳转函数
  const Navigate = useNavigate()
  const location = useLocation()
  const [openKeys, setOpenKeys] = useState([''])
  const [current, setCurrent] = useState(location.pathname)

  // 刷新时被选中的menu二级菜单初始化的展开问题
  useEffect(() => {
    const refreshThePage = () => {
      let pathname = location.pathname
      for (let index = 0; index < items.length; index++) {
        const element: MenuItem = items[index]
        // console.log(element,'elementelement');
        if (
          element.children &&
          element?.children.find((i1:MenuItem) => i1.key === pathname)
        ) {
          setOpenKeys([element.key])
          break
        }
      }
    }
    refreshThePage()
  }, [])
  // 菜单点击
  const onClick: MenuProps['onClick'] = (e) => {
    Navigate(e.key)
    setCurrent(e.key)
  }
  // 展开/关闭的回调
  const onOpenChange: MenuProps['onOpenChange'] = (keys: string[]) => {
    setOpenKeys([keys[keys.length - 1]])
  }
  return (
    <Menu
      theme="dark"
      mode="inline"
      items={items}
      onClick={onClick}
      onOpenChange={onOpenChange}
      openKeys={openKeys}
      selectedKeys={[current]}
    />
  )
}

export default HomeMenu
